

package com.jb.web.renderer;

import com.jb.faces.component.UIComponent;
import com.jb.web.bean.Grid;
import com.jb.web.bean.ListBean;
import com.jb.web.bean.TableCell;
import com.jb.web.bean.TableColumn;
import com.jb.web.bean.TableHeader;
import com.jb.web.bean.TableRow;
import com.jb.web.bean.UIComponentImpl;
import com.jb.web.context.WebContext;

import java.util.Iterator;

public class GridRenderer extends DefaultRenderer {

    private void $init$() {
        tableWidth = 518;
        tableHeight = 200;
        innerTableWidth = 487;
        headerHeight = 20;
        defaultColumnWidth = 90;
    }

    public StringBuffer renderBegin(WebContext ctx, UIComponent itemToRender) {
        Grid tableData = (Grid)itemToRender;
        initialize(ctx, tableData);
        StringBuffer html = new StringBuffer();
        id = tableData.getClientId();
        tableWidth = innerTableWidth + 31;
        String widthStr = tableData.getHeight();
        if (widthStr != null && widthStr.length() > 0) {
            widthStr = widthStr.substring(0, widthStr.length() - 2);
            tableHeight = Integer.parseInt(widthStr);
        }
        String tableClass = 
            tableData.getStyleClass() != null ? (new StringBuilder()).append(" ").append(tableData.getStyleClass()).toString() : 
            "";
        html.append("<div ").append(getEditScript(ctx, 
                                                  tableData)).append((new StringBuilder()).append("onmouseover=\"JBTable.onTableMouseOver(event,'").append(id).append("');\"").toString()).append((new StringBuilder()).append("onmousedown=\"JBTable.onTableMouseDown(event,'").append(id).append("');\"").toString()).append((new StringBuilder()).append("onmouseup=\"JBTable.onTableMouseUp(event,'").append(id).append("');\"").toString()).append((new StringBuilder()).append("onmousemove=\"JBTable.onTableMouseMove(event,'").append(id).append("');\"").toString()).append(addTagProperty("style", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    (new StringBuilder()).append(tableData.getStyle(ctx)).append("position:relative;").toString(), 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    null)).append(addTagProperty("editable", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 tableData.isEditable() ? 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 "true" : 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 null, 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 null)).append(addTagProperty("jb_select_mode", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              "row", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              null)).append(addTagProperty("class", 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           (new StringBuilder()).append("jb_grid_table").append(tableClass).toString(), 
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           null)).append(">");
        html.append("<div id=\"").append(id).append("resizer\" dragBox=\"").append(id).append("\" draggable=\"true\" cloneOnDrag=\"true\" style=\"position:absolute;display:none;\" class=\"jb_col_resizer\" ></div>");
        html.append(renderHeader(ctx, tableData));
        return html;
    }

    private void initialize(WebContext ctx, Grid table) {
        TableHeader th = table.getHeader(ctx);
        int i = 0;
        Iterator iter = th.getChildrenSorted(null).iterator();
        columnStyleClass = new String[th.getCols()];
        fieldNames = new String[th.getCols()];
        columnWidth = new int[th.getCols()];
        innerTableWidth = 0;
        while (iter.hasNext()) {
            TableCell tc = (TableCell)iter.next();
            String widthStr = tc.getWidth();
            if (tc instanceof TableColumn) {
                TableColumn tcc = (TableColumn)tc;
                columnStyleClass[i] = 
                        tcc.getColumnClass() != null ? tcc.getColumnClass() : 
                        "";
                fieldNames[i] = 
                        tcc.getFieldName() != null ? tcc.getFieldName() : "";
            }
            if (widthStr == null || widthStr.length() == 0)
                columnWidth[i] = defaultColumnWidth;
            else
                try {
                    widthStr = widthStr.substring(0, widthStr.length() - 2);
                    columnWidth[i] = Integer.parseInt(widthStr);
                } catch (Exception e) {
                    columnWidth[i] = defaultColumnWidth;
                }
            innerTableWidth += 5 + columnWidth[i];
            i++;
        }
    }

    private StringBuffer renderHeader(WebContext ctx, Grid table) {
        StringBuffer html = new StringBuffer();
        html.append("<div ").append(addTagProperty("id", 
                                                   (new StringBuilder()).append(id).append("_hc").toString(), 
                                                   null)).append(">");
        html.append("<div style=\"width:100%;overflow:hidden;\"").append(addTagProperty("id", 
                                                                                        (new StringBuilder()).append(id).append("_h").toString(), 
                                                                                        null)).append(">");
        html.append("<div style=\"width:2000px;\"").append(" class=\"jb_hd jb_header_offset\">");
        html.append((new StringBuilder()).append("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" id=\"").append(id).append("_t\" class=\"").append(id).append("_row\" style=\"width: ").append(innerTableWidth).append("px;\"><thead>").toString());
        html.append("<tr class=\"jb_hd_row\" ").append("> ");
        TableHeader th = table.getHeader(ctx);
        String firstCol = "_first";
        Iterator iter = th.getChildrenSorted(null).iterator();
        int i = 0;
        boolean sortable = false;
        boolean editable = false;
        while (iter.hasNext()) {
            TableCell tc = (TableCell)iter.next();
            String dataType = null;
            if (tc instanceof TableColumn) {
                sortable = ((TableColumn)tc).isSortable();
                dataType = ((TableColumn)tc).getDataType();
                editable = ((TableColumn)tc).isEditable();
            }
            html.append("<td style=\"width:").append(columnWidth[i]).append("px;\"").append(addTagProperty("class", 
                                                                                                           "jb_cell", 
                                                                                                           null)).append(addTagProperty("jb_data_type", 
                                                                                                                                        dataType, 
                                                                                                                                        null)).append(addTagProperty("jb_editable", 
                                                                                                                                                                     sortable ? 
                                                                                                                                                                     "true" : 
                                                                                                                                                                     null, 
                                                                                                                                                                     null)).append(addTagProperty("jb_field_name", 
                                                                                                                                                                                                  fieldNames[i], 
                                                                                                                                                                                                  null)).append(addTagProperty("jb_sortable", 
                                                                                                                                                                                                                               sortable ? 
                                                                                                                                                                                                                               "true" : 
                                                                                                                                                                                                                               null, 
                                                                                                                                                                                                                               null)).append(getEditScript(ctx, 
                                                                                                                                                                                                                                                           tc));
            String sortBy = "";
            if (table instanceof ListBean) {
                ListBean bean = (ListBean)table;
                sortBy = 
                        bean.getSortBy() == null || !bean.getSortBy().equals((new StringBuilder()).append("").append(i).toString()) ? 
                        "" : bean.isReverse() ? "jb_asc" : "jb_desc";
            }
            html.append("><div id=\"").append(tc.getClientId()).append("_c\"");
            String classString = 
                (new StringBuilder()).append("jb_hd_inner").append(i != 0 ? 
                                                                   "" : 
                                                                   firstCol).append(" ").append(id).append("_").append(i).append(" ").append(sortBy).append(" ").append(columnStyleClass[i]).toString();
            html.append(addTagProperty("class", classString, null));
            html.append((new StringBuilder()).append("onmouseover=\"JBTable.onColumnMouseOver(event,'").append(id).append("',").append(i).append(");\"").toString()).append((new StringBuilder()).append("onmousedown=\"JBTable.onColumnMouseDown(event,'").append(id).append("',").append(i).append(");\"").toString()).append((new StringBuilder()).append("onmouseup=\"JBTable.onColumnMouseUp(event,'").append(id).append("',").append(i).append(");\"").toString()).append((new StringBuilder()).append("onmousemove=\"JBTable.onColumnMouseMove(event,'").append(id).append("',").append(i).append(");\"").toString()).append(" style=\"width:").append(columnWidth[i]).append("px;\" ").append((new StringBuilder()).append("onmouseout=\"JBTable.onColumnMouseOut(event,'").append(id).append("',").append(i).append(");\" >").toString());
            html.append(tc.getValue());
            html.append(E2);
            i++;
        }
        html.append(E1);
        return html;
    }

    protected StringBuffer renderRow(WebContext ctx, TableRow row, int rowNo, 
                                     boolean selected) {
        StringBuffer html = new StringBuffer();
        String rid = row.getClientId(ctx);
        html.append("<div ").append(getEditScript(ctx, row));
        if (!selected)
            html.append(" class=\"jb_row ");
        else
            html.append(" class=\"jb_row_selected ");
        html.append(id).append("_row\" style=\"width:").append(innerTableWidth).append("px;\" ");
        StringBuffer sb = 
            new StringBuffer((new StringBuilder()).append(rid).append("','").append(id).toString());
        html.append("onmouseover=\"JBTable.onRowMouseOver(event,'").append(sb).append("');\" onclick=\"JBTable.onRowSelect(event,'").append(sb).append("');\" onmousemove=\"JBTable.onRowMouseMove(event,'").append(sb).append("');\" onmouseout=\"JBTable.onRowMouseOut(event,'").append(sb).append("');\"> <table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"jb_row_table ").append(id).append("_row\" style=\"width: ").append(innerTableWidth).append("px;\"><tbody> <tr >");
        Iterator iter = row.getChildrenSorted(null).iterator();
        int i = 0;
        String firstCol = "_first";
        while (iter.hasNext()) {
            TableCell tc = (TableCell)iter.next();
            String cid = 
                (new StringBuilder()).append(id).append("_").append(rowNo).append("_").append(i).toString();
            tc.setClientId(cid);
            html.append("<td style=\"width: ").append(columnWidth[i]).append("px;\"");
            html.append(addTagProperty("class", "jb_cell", 
                                       null)).append(getEditScript(ctx, tc));
            html.append("><div id=\"").append(tc.getClientId()).append("_c\" class=\"jb_cell_inner").append(i != 
                                                                                                            0 ? 
                                                                                                            "" : 
                                                                                                            firstCol).append(" ").append(id).append("_").append(i).append(" ").append(columnStyleClass[i] != 
                                                                                                                                                                                      null ? 
                                                                                                                                                                                      "" : 
                                                                                                                                                                                      columnStyleClass[i]).append(" \" style=\"width: ").append(columnWidth[i]).append("px;\">");
            html.append(renderCell(ctx, tc));
            html.append("</div></td>");
            i++;
        }
        html.append("</tr></tbody></table></div>");
        return html;
    }

    public StringBuffer renderCell(WebContext pCtx, UIComponent itemToRender) {
        TableCell tableData = (TableCell)itemToRender;
        StringBuffer html = new StringBuffer();
        Iterator iter = tableData.getFacetsAndChildrenSorted(null).iterator();
        boolean childrenPainted = false;
        while (iter.hasNext()) {
            UIComponentImpl aSect = (UIComponentImpl)iter.next();
            if (isVisible(pCtx, aSect)) {
                html.append(aSect.render(pCtx));
                childrenPainted = true;
            }
        }
        if (!childrenPainted) {
            String strValue = getValue(pCtx, tableData);
            html.append(isEmptyString(strValue) ? "" : strValue);
        }
        return html;
    }

    public StringBuffer renderChildren(WebContext ctx, 
                                       UIComponent itemToRender) {
        StringBuffer html = 
            (new StringBuffer("<div onScroll=\"JBTable.synchronizeScroll('")).append(id).append("');\" id=\"").append(id).append("_b\" style=\"overflow:auto; width: 100%; height: ").append(tableHeight - 
                                                                                                                                                                                             headerHeight).append("px;\">");
        html.append(renderRows(ctx, itemToRender));
        html.append("</div>");
        return html;
    }

    protected StringBuffer renderRows(WebContext ctx, 
                                      UIComponent itemToRender) {
        StringBuffer html = new StringBuffer();
        Grid tableData = (Grid)itemToRender;
        for (int i = 0; i < tableData.getRows(); i++)
            try {
                TableRow row = tableData.getRow(i);
                html.append(renderRow(ctx, row, i, false));
            } catch (Exception e) {
                ctx.addErrorMessage(tableData, e.getMessage());
            }

        if (tableData.getRows() == 0)
            html.append("<tr><td>At least one row for a table</td></tr> ");
        return html;
    }

    public StringBuffer renderEnd(WebContext ctx, UIComponent itemToRender) {
        StringBuffer html = new StringBuffer();
        return html.append("</div></div>");
    }

    public GridRenderer() {
        $init$();
    }

    String id;
    int tableWidth;
    int tableHeight;
    int innerTableWidth;
    int headerHeight;
    String columnStyleClass[];
    String fieldNames[];
    int columnWidth[];
    int defaultColumnWidth;
    private static String E1 = 
        "</tr></thead></table></div></div> <div class=\"x_clear\"/></div>";
    private static String E2 = 
        "<img class=\"jb_sort_icon\" src=\"resources/images/empty.gif\"/></div></td>";

}
